package com.se.service;

import com.se.dao.mysql.ActDao;
import com.se.dao.mysql.ApplyDao;
import com.se.domain.mysql.ActivityDO;
import com.se.domain.mysql.ApplyDO;
import com.se.domain.mysql.RecordDO;
import com.se.domain.request.param.ApplyActParam;
import com.se.domain.request.param.ApplyQParam;
import com.se.exception.ResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ActTranService {
    @Autowired
    ActDao actDao;
    @Autowired
    ApplyDao applyDao;

    @Transactional
    public ApplyDO applyAct(Long userId, ActivityDO activityDO, ApplyActParam param) throws ResultException {
        actDao.incrementApplyNum(activityDO.getActId());
        Long applyId = applyDao.getApplyIdByQnIdAndUserId(activityDO.getQnId(), userId);
        ApplyDO applyDO = applyDao.createApply(userId, activityDO.getActId(), activityDO.getQnId());

        if(applyId != null){
            applyDO.setApplyId(applyDO.getApplyId());
        }

        List<RecordDO> recordDOList = new ArrayList<>();
        for (ApplyQParam qParam : param.getQn()) {
            RecordDO recordDO = new RecordDO(applyDO.getApplyId(), qParam.getQId(), qParam.getAns(), userId);
            recordDOList.add(recordDO);
        }
        applyDao.createRecords(recordDOList);
        return applyDO;

    }

    @Transactional
    public void cancelApplyAct(Long applyId, Long actId){
        actDao.decrementApplyNum(actId);
        applyDao.cancelApply(applyId);
    }
}
